<template>
  <el-dialog
    :title="isEdit?'修改':'新增'"
    :visible.sync="visible"
    @close="$emit('update:show', false)"
  >
    <el-form label-width="auto" :rules="rules" :model="params" ref="editForm" size="small">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
          <el-form-item label="AppId">
            <el-input placeholder="请输入应用名称" v-model="params.appId" disabled></el-input>
          </el-form-item>
          <el-form-item label="应用名称" prop="appName">
            <el-input placeholder="请输入应用名称" v-model="params.appName"></el-input>
          </el-form-item>
          <el-form-item label="英文名称" prop="appNameEn">
            <el-input placeholder="请输入英文名称" v-model="params.appNameEn"></el-input>
          </el-form-item>
          <el-form-item label="应用类型" prop="appType">
            <dictionary-select v-model="params.appType" parent-code="system-app-type"></dictionary-select>
          </el-form-item>
          <el-form-item label="应用官网">
            <el-input type="textarea" v-model="params.website"></el-input>
            <div class="form-item-tip">多个地址使用,逗号隔开</div>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch
              v-model="params.status"
              :active-value='1'
              :inactive-value='0'
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="启用">
            </el-switch>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" placeholder="可输入备注" v-model="params.remark"></el-input>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="开发信息" name="second">
          <el-form-item label="AppKey">
            <el-input placeholder="由后台自动生成，保存信息之后可自行查看" v-model="systemAppClient.apiKey" disabled></el-input>
          </el-form-item>
          <el-form-item label="SecretKey">
            <el-input placeholder="由后台自动生成，保存信息之后可自行查看" v-model="systemAppClient.secretKey" disabled></el-input>
          </el-form-item>
          <!--授权类型-->
          <!--授权码模式 客户端模式 密码模式 简化模式 刷新令牌-->
          <el-form-item label="授权类型">
            <dictionary-checkbox v-model="systemAppClient.grantTypes"
                                 parent-code="system-auth-type"></dictionary-checkbox>
          </el-form-item>
          <el-form-item label="用户授权范围">
            <dictionary-checkbox v-model="systemAppClient.scopes"
                                 parent-code="system-auth-scopes"></dictionary-checkbox>
          </el-form-item>
          <el-form-item label="访问令牌有效期">
            <el-input-number v-model="systemAppClient.accessTokenValidity" :min="0"></el-input-number>&nbsp;秒
            <span class="text-muted"> = {{humanizeTime(systemAppClient.accessTokenValidity)}}</span>
          </el-form-item>
          <el-form-item label="刷新令牌有效期">
            <el-input-number v-model="systemAppClient.refreshTokenValidity" :min="0"></el-input-number>&nbsp;秒
            <span class="text-muted"> = {{humanizeTime(systemAppClient.refreshTokenValidity)}}</span>
          </el-form-item>
          <el-form-item label="第三方登陆回调地址">
            <el-input type="textarea" v-model="systemAppClient.redirectUrls"></el-input>
            <div class="form-item-tip">多个地址使用,逗号隔开</div>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="授权接口" name="third">
          <auth-api-mod :auth-id="params.appId" auth-type="app" @change="authApiChange"></auth-api-mod>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="saveEdit">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import AuthApiMod from '../common/AuthApiMod'
  import DictionarySelect from '../../common/DictionarySelect'
  import DictionaryCheckbox from '../../common/DictionaryCheckbox'

  export default {
    name: "AddEditDialog",
    components: {
      AuthApiMod,
      DictionarySelect,
      DictionaryCheckbox
    },
    props: {
      show: {
        type: Boolean,
        default: false
      },
      editData: null
    },
    watch: {
      show: {
        handler() {
          this.visible = this.show;
          if (!this.editData) {
            for (let k in this.params) {
              this.params[k] = '';
            }
            let randomNum = Math.floor(Math.random() * (8999 - 1000)) + 1000;
            this.params.appId = this.$moment().valueOf() + '' + randomNum;
            this.systemAppClient.accessTokenValidity = 43200;
            this.systemAppClient.refreshTokenValidity = 2592000;
            this.params.clientState = 1;
            this.params.status = 1;
            this.isEdit = false;
          }
        },
        immediate: true,
        deep: true
      },
      editData: {
        handler() {
          if (this.editData) {
            this.params.appId = this.editData.appId;
            this.query();
            this.isEdit = true;
          }
        },
        immediate: true,
        deep: true
      }
    }
    ,
    data() {
      return {
        activeName: 'first',
        visible: this.show,
        isEdit: false,
        params: {
          appId: '',
          apiKey: '',
          secretKey: '',
          appName: '',
          appNameEn: '',
          appType: '',
          website: '',
          status: 1,
          appDesc: '',
          systemAppClient: '',
          authorities: ''
        },
        systemAppClient: {
          apiKey: '',
          secretKey: '',
          grantTypes: '',
          accessTokenValidity: 43200,
          refreshTokenValidity: 2592000,
          redirectUrls: '',
          scopes: ''
        },
        informationData: {
          remark: '',
          secretKey: '',
          isPersist: 0
        },
        rules: {
          appName: [
            {required: true, message: '应用名称不能为空', trigger: 'blur'}
          ],
          appNameEn: [
            {required: true, message: '英文名称不能为空', trigger: 'blur'}
          ],
          appType: [
            {required: true, message: '应用类型必选', trigger: 'blur'}
          ],
          grantTypes: [
            {required: true, message: '授权类型必选', trigger: 'blur'}
          ],
          scopes: [
            {required: true, message: '用户授权范围必选', trigger: 'blur'}
          ],
          accessTokenValidity: [
            {required: true, message: '访问令牌有效期不能为空', trigger: 'blur'}
          ],
          refreshTokenValidity: [
            {required: true, message: '刷新令牌有效期不能为空', trigger: 'blur'}
          ],
        },
        selectedApis: []
      }
    },
    mounted() {

    },
    methods: {
      query() {
        this.api.get('/bucket-system/system/app/' + this.params.appId + '/info')
          .then((data) => {
            let d = data.data;
            this.systemAppClient = data.data.systemAppClient;
            for (let k in this.params) {
              this.params[k] = d[k] ? d[k] : null;
            }
            this.params.systemAppClient = data.data.systemAppClient;
            this.params.systemAppClient.secretKey = data.data.secretKey;
            this.params.systemAppClient.apiKey = data.data.apiKey;
          });
      },
      saveEdit: function () {
        this.$refs['editForm'].validate((valid) => {
          if (valid) {
            let _url = '';
            if (!this.isEdit) {
              _url = '/bucket-system/system/app/add';
            } else {
              _url = '/bucket-system/system/app/update';
            }

            this.params.systemAppClient = this.systemAppClient;
            this.api.post(_url, this.params)
              .then((data) => {
                if (data.code === 200) {

                  if (this.selectedApis.length > 0)
                    this.saveAuthApis();

                  this.visible = false;
                  this.$message({
                    message: '保存成功',
                    type: 'success'
                  });
                  this.$parent.query();
                } else {
                  this.$message.error(data.data);
                }
              });
          } else {
            return false;
          }
        });
      },
      saveAuthApis() {
        this.api.post('/bucket-system/gateway/api/interface/bind', {
          authId: this.params.appId, authType: 'app', intId: this.selectedApis.join(',')
        });
      },
      authApiChange(valArr) {
        this.selectedApis = valArr;
      },
      humanizeTime(sec) {
        if (sec)
          return this.$moment.duration(sec, "seconds").humanize();
        return '';
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss">
  .el-drawer__body {
    overflow: auto;
  }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  .edit-drawer {

  .demo-drawer__content {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 0 20px 20px 20px;
    overflow: auto;

  form {
    flex-grow: 1;
  }

  .demo-drawer__footer {
    display: flex;

  button {
    flex: 1;
  }

  }
  }
  }

</style>
